const https = require('https');
const SQLHelper = require('./SQLHelper');//引入SQLHelper
const snowflake = require('./snowflake');//雪花算法生成id
const { formatTime } = require('./util')//日期

//token缓存(每个用户都有自己的token)
let tokens = {}
module.exports = function(app){
  /**
 * 登录拦截中间件
 */
function loginRouter (req,res,next){
  let token = req.headers.token
  if(token){
    //通过token获取用户信息
   let session = tokens[req.headers.token]
   if(session){
    req.session = session
    next()
   }
   else{
    res.status(406).send({errorMsg:'当前用户未登录'})
   }
  }else{
    res.status(405).send({errorMsg:'缺少token,请先进行登录'})
  }
   

}
//对带'/wx'的接口进行登录拦截---让初登录的所有小程序接口都先验证登录
app.use('/wx',loginRouter)

// //日期格式化
// const formatTime = date => {
//   const year = date.getFullYear()
//   const month = date.getMonth()
//   const day = date.getDate()
//   const hour = date.getHours()
//   const minute = date.getMinutes()
//   const second = date.getSeconds()

//   return `${[year,month,day].map(formatNumber).join('/')} ${[hour,minute,second].map(formatNumber).join(':')}`
// }
// const formatNumber = n => {
//   n = n.toString()
//   return n[1] ? n : `0${n}`
// }

//微信登录
app.get('/wxlogin', (req,res,next) => {
  // console.log(req)
  let code = req.query.code
  let appid = 'wx6d47c603af6377f1'
  let secret = 'ac667e21450577b8844284d4e2e8e817'
  https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
        ret.on('data',(ret) => {
          ret = JSON.parse(ret.toString())
          let openid = ret.openid
          if(!openid){
            res.send({errorMsg: ret.errMsg || '获取openid错误'})
          }else{
            let queryMember = `select * from member where openId ='${openid}'`
            SQLHelper(queryMember).then(membersRet => {
              console.log(membersRet)
              if(membersRet.length){//用户已经存在
                //挂载到req
                req.member = membersRet[0]
                next()
              }else{//用户不存在 使用openid注册用户
                SQLHelper(`INSERT INTO member(openId) values('${openid}')`).then(newMember => {
                  //注册成功 返回新用户信息
                  SQLHelper(queryMember).then(newMember => {
                    //挂载到req
                    req.member = membersRet[0]
                    next()
                  })

                })
                      
              }
            })
          }
            
        });

        }).on('error',(e) => {
            console.error(e);
            res.status(406).send('Not Acceptable')
        }) ;

},(req,res) => {
  let member = req.member
  let token = snowflake() //当前登录所产生的token
  //缓存到token到session
  SQLHelper(`
    INSERT INTO session(id,userId,userName,inTime,platform) 
    VALUES(${token},'${member._id}','${member.nickName}','${formatTime(new Date())}','wx')
    `).then(ret => {
      console.log(ret,req)
      res.send({
        nickName:member.nickName,
        token,
        openId:member.openId,
        avatarUrl:member.avatarUrl,
        _id:member._id
      })//将数据返回给前端
    })
  // tokens[token] = member
  // member.token = token
})

/**
 * 更新数据
put函数数据放在body里
修改用户信息
/wx/member---接口
 */
app.put('/wx/member',(req,res) => {
  let userInfo = req.body
  console.log(userInfo,req.query)
  SQLHelper(`
  update member 
  set nickName = '${userInfo.nickName}',avatarUrl = '${userInfo.avatarUrl}'
  where _id = '${req.session._id}'
  `).then(ret => {
    console.log(ret)
    res.send({})//将数据返回给前端
  })
})
/**
 * 获取收货地址列表
 * memberId(用户Id)是必填的
 */
app.get('/wx/address',(req,res) => {
  // console.log(req.headers,req.headers.token,tokens[req.headers.token])
  //通过token获取用户信息
  // let session = tokens[req.headers.token]
  // console.log(tokens[req.headers.token])
  // //判断用户地址是否传入
  // let memberId = session._id
  if(req.session._id){
    SQLHelper(`
    select * from address where state = 1 and memberId = '${req.session._id}'
    `).then(ret => {
      console.log(ret)
      res.send(ret)//将数据返回给前端
    })
  }else
  {
    res.send({errorMsg:'请传入memberId'})
  }
})
/**
 * 获取收货地址详情
 * addressId (_id)是必填的
 */
 app.get('/wx/address/detail',(req,res) => {
  //判断用户地址是否传入
  if(req.query.addressId){
    SQLHelper(`
    select * from address where _id = '${req.query.addressId}'
    `).then(ret => {
      console.log(ret)
      res.send(ret.length ? res[0] : {errorMsg:'未获取到地址详情'})//将数据返回给前端
    })
  }else
  {
    res.send({errorMsg:'请传入addressId'})
  }
})
/**
 * 新增收货地址
 * memberId(用户Id)是必填的
 * receiver(收货人)是必填的
 * phone(手机号)是必填的
 * city(省市区)是必填的
 * area(详细地址)非必填
 */
 app.post('/wx/address',(req,res) => {
  //判断用户地址是否传入
  if(req.session._id && req.body.receiver && req.body.phone && req.body.city){
    SQLHelper(`
    INSERT INTO address(state,memberId,receiver,phone,city,area) 
    VALUES(1,'${req.session._id}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area || ''}')
    `).then(ret => {
      console.log(ret,req)
      res.send(ret)//将数据返回给前端
    })
  }else
  {
    res.send({errorMsg:'传入参数错误'})
  }
})
/**
 * 修改收货地址
 * addressId _id是必填的
 * receiver(收货人)是非必填的
 * phone(手机号)是非必填的
 * city(省市区)是非必填的
 * area(详细地址)非必填
 */
 app.put('/wx/address',(req,res) => {
  if(req.body.addressId){
    //需要修改的项
    let updateKey = ['receiver','phone','city','area']
    let updateValues = []
    for(let i=0; i< updateKey.length ; i++){
        let key = updatekey[i],value = req.body[key]
      if(value) updateValues.push(`${key}='${value}'`) //判断哪些需要修改
    }
    SQLHelper(`UPDATE address set ${updateValues.join(',')}WHERE _id = ${req.body.addressId}`).then(ret => {
      console.log(ret,req)
      res.send(ret)//将数据返回给前端
    })
  }else
  {
    res.send({errorMsg:'传入参数错误'})
  }
})
/**
 * 修改为默认地址
 * 要求传入addressId对应_id必填
 * memberId(用户Id)是必填的
 * isDefault 非必填
 */
app.put('/wx/address/default',(req,res) => {
  let addressId = req.body.addressId
  let memberId = req.session._id
  let isDefault = req.body.isDefault == 1 ? 1 : 0
  if(addressId){
    if(isDefault == 1){//设置默认地址
      //取消其他默认地址
      SQLHelper(`
      UPDATE address
      SET isDefault = 0
      WHERE isDefault = 1 AND memberId = '${memberId}'
      `).then(ret => {
        SQLHelper(`
        UPDATE address
        SET isDefault = 1
        WHERE _id = '${addressId}'
        `).then(ret => {
          console.log(ret,req)
          res.send(ret)//将数据返回给前端
        })
      })
    }else{//取消默认地址
      SQLHelper(`
        UPDATE address
        SET isDefault = 0
        WHERE _id = '${addressId}'
        `).then(ret => {
          console.log(ret,req)
          res.send(ret)//将数据返回给前端
        })
    }
  }else{
    res.send({errorMsg:'请传入正确addressId'})
  }

})
/**
 * 删除地址---逻辑删除
 * 要求传入addressId对应_id必填
 * 
 */
 app.delete('/wx/address',(req,res) => {
  let addressId = req.body.addressId
  // console.log('这是addressId',addressId)
  if(addressId){
    SQLHelper(`
    UPDATE address
    SET state = 0
    WHERE _id = '${addressId}'
    `).then(ret => {
        res.send(ret)//将数据返回给前端
    })
  }else{
    res.send({errorMsg:'请传入正确addressId'})
  }

})

}


/**
 * 
 * //createServer创建一个服务  req---请求信息
http.createServer((req, res) => {
  console.log(req.url)
  // res.writeHead(200);
  let code = req.url.split('?')[1].split('=')[1]
  let appid = 'wx6d47c603af6377f1';
  let secret = 'ac667e21450577b8844284d4e2e8e817';
  https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
  console.log('statusCode:', ret.statusCode);
  console.log('headers:', ret.headers);

  ret.on('data', (d) => {
    // process.stdout.write(d);
    console.log(d)
    res.end('hello world\n');
    res.writeHead(200);
    res.end(d.toString());
  });

}).on('error', (e) => {
    console.error(e);
});
  // res.end('hello world\n');//里面的数据返回给前端
}).listen(8000); //listen监听8000窗口

 */

